package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MenuDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service(interfaceClass = MenuService.class)
public class MenuServiceImpl implements MenuService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private MenuDao menuDao;


    @Override
    public List<Menu> findMenuByUsername(String username) {
        User user = userDao.findUserByUsername(username);
        if (user == null) {
            return null;
        }
        Integer userId = user.getId();
        Set<Role> roles = roleDao.findRoleListByUserId(userId);
        List<Menu> menus = new ArrayList<>();
        if (roles != null && roles.size() > 0) {
            for (Role role : roles) {
                menus = menuDao.findMenuListByRoleId(role.getId());
                if (menus != null && menus.size() > 0){
                    for (Menu menu : menus) {
                        List<Menu> children = menuDao.findMenuListById(menu.getId());
                        menu.setChildren(children);
                    }
                }
            }
        }
        return menus;
    }
}
